package gouhuo.allbugs.top.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import gouhuo.allbugs.top.model.domain.User;
import gouhuo.allbugs.top.model.vo.UserVO;
import gouhuo.allbugs.top.service.impl.UserServiceImpl;
import gouhuo.allbugs.top.constant.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 七牛云上传工具类
 */
@Slf4j
@Component
public class QiNiuUtil {

    @Resource
    private UserServiceImpl userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final static String ACCESS_KEY = "70SYGG8w_FfLW_RBKUVkUDRHK3BDQPGqHbI9KOin";
    private final static String SECRET_KEY = "zRf9RzfYOswRu-7AvNr1UXrR88EMwbKv-B6FIB1A";
    private final static String BUCKET = "allbugs";
    private final static String DOMAIN = "cdn.allbugs.top";
    static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    public String getToken() {
        return auth.uploadToken(BUCKET);
    }

    public boolean saveImage(MultipartFile file, HttpServletRequest request) throws IOException {
        Configuration cfg = new Configuration(Region.huabei());
        UploadManager uploadManager = new UploadManager(cfg);
        cfg.useHttpsDomains = false;
        try {
            int dotPos = file.getOriginalFilename().lastIndexOf(".");
            if (dotPos < 0) {
                return false;
            }
            String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
            //todo 将文件名价格统一前缀 /cdn
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
            // 调用put方法上传
            Response res = uploadManager.put(file.getBytes(), fileName, getToken());
            // 打印返回的信息
            if (res.isOK() && res.isJson()) {
                // 返回这张存储照片的地址
                DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
                String finalUrl = "http://" + DOMAIN + "/" + putRet.key;
                UserVO userVO = userService.getLoginUser(request, null);
                Long userId = userVO.getId();
                User user = userService.getById(userId);
                user.setAvatarUrl(finalUrl);
                boolean update = userService.updateById(user);
                if (update) {
                    //修改登录信息里的头像
                    stringRedisTemplate.opsForHash().put(RedisConstants.LOGIN_USER_KEY + request.getSession().getId(), "avatarUrl", finalUrl);
                    //修改访客俩表里的头像
                    userService.updateRedisByUser("visitor:full:*", "avatarUrl", finalUrl, userId, "visitor");
                    //修改好友列表里的头像
                    userService.updateRedisByUser("friends:list:*", "friendUrl", finalUrl, userId, "friend");
                }
                return update;
            } else {
                log.error("七牛异常:" + res.bodyString());
                return false;
            }
        } catch (QiniuException e) {
            // 请求失败时打印的异常的信息
            log.error("七牛异常:" + e.getMessage());
            return false;
        }
    }
}
